package com.example.offer.no0018.impl;

import com.example.offer.no0018.ListNode;
import com.example.offer.no0018.Solution;

/**
 * @author yumuhui <yumuhui@kuaishou.com>
 * 时间复杂度：O(n)，其中 n 是链表的长度。需要遍历链表一次。
 * 空间复杂度：O(1)。
 * Created on 2021-05-17
 */
public class SolutionImpl implements Solution {

    @Override
    public ListNode deleteNode(ListNode head, int val) {

        if (head == null) {
            return null;
        }

        if (head.val == val) {
            return head.next;
        }

        ListNode pre = head;
        ListNode curr = head.next;
        while (curr != null && curr.val != val) {
            pre = curr;
            curr = curr.next;
        }

        if (curr != null) {
            pre.next = curr.next;
        }

//        ListNode cur = head;
//        while (cur.next != null && cur.next.val != val) {
//            cur = cur.next;
//        }
//        if (cur.next != null) {
//            cur.next = cur.next.next;
//        }

        return head;
    }
}
